package cn.yonyong.base.project.controller;

import cn.yonyong.base.project.service.ImageService;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Describtion 上传预览图片并保存
 * @Author yonyong
 * @Date 2019/9/19 17:09
 * @Version 1.0.0
 **/
@Api(value = "/upload", tags = "图片处理")
@RestController
@RequestMapping("upload")
@CrossOrigin
public class UploadFileController {

    @Autowired
    private ImageService imageService;

    private final static Logger logger = LoggerFactory.getLogger(UploadFileController.class);

    @ApiOperation(value = "上传图片,存储路径:E:\\mycode\\gitee\\Base-Project\\target\\first\\upload")
    @RequestMapping(value = "image",method = RequestMethod.POST)
    public JSONObject uploadImage(@RequestParam("file0") MultipartFile file,HttpServletRequest request) throws IOException {
        Map<String,Object> result_map = new HashMap<>();
        logger.info("arrive here");
        if(!file.isEmpty()) {
            logger.info(file.getOriginalFilename());
            String absolute_name = file.getOriginalFilename();  //原本的文件名
            long file_size = file.getSize();
            String now_name = System.currentTimeMillis() + file.getOriginalFilename();//现在的文件名是时间戳加原文件名，出现图片相同时，读取不出来的bug
            String realPath = request.getSession().getServletContext().getRealPath("/upload/");//将文件保存在当前工程下的一个upload文件
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, now_name));//将文件的输入流输出到一个新的文件
            now_name="upload/"+now_name;
            result_map.put("result","yes");//返回yes,表示存储成功，可以使用try,catch来捕捉错误，这里偷懒不用

            //保存进数据库
            Map<String,Object> temp_map = imageService.saveImage(now_name,absolute_name,file_size);
            result_map.put("insert",temp_map.get("insert"));
        }
        return (JSONObject) JSONObject.toJSON(result_map);
    }

    @ApiOperation(value = "文件列表")
    @RequestMapping(value = "getList",method = RequestMethod.POST)
    public JSONObject getList(){
        Map<String,Object> result_map = new HashMap<>();
        result_map = imageService.getList();
        return (JSONObject) JSONObject.toJSON(result_map);
    }
}
